package com.rongji.dfish.demo.editor.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rongji.dfish.base.Utils;
import com.rongji.dfish.demo.pub.view.PubView;
import com.rongji.dfish.framework.controller.BaseController;
import com.rongji.dfish.ui.command.AjaxCommand;
import com.rongji.dfish.ui.command.BeforeCommand;
import com.rongji.dfish.ui.command.CommandGroup;
import com.rongji.dfish.ui.command.DialogCommand;
import com.rongji.dfish.ui.command.JSCommand;
import com.rongji.dfish.ui.command.SubmitCommand;
import com.rongji.dfish.ui.form.Spinner;
import com.rongji.dfish.ui.form.Text;
import com.rongji.dfish.ui.form.Textarea;
import com.rongji.dfish.ui.form.XBox;
import com.rongji.dfish.ui.helper.FlexGrid;
import com.rongji.dfish.ui.layout.GridLayout;
import com.rongji.dfish.ui.layout.HorizontalLayout;
import com.rongji.dfish.ui.layout.View;
import com.rongji.dfish.ui.layout.grid.GridColumn;
import com.rongji.dfish.ui.layout.grid.Td;
import com.rongji.dfish.ui.layout.grid.Tr;
import com.rongji.dfish.ui.widget.Button;
import com.rongji.dfish.ui.widget.Html;

/**
 * 用要树的特色功能展示
 * 这个范例只是为了展示功能特色，所以没有分MVC 来写，并不利于工程的建立。
 * @author DFish Team
 *
 */
@Controller
@RequestMapping("/gridShow")
public class GridShowController extends BaseController{
	@RequestMapping("/gridEdit")
	@ResponseBody
	public Object gridEdit(HttpServletRequest request) throws Exception {
		
		View view=new View();
		HorizontalLayout root=new HorizontalLayout("root").setScroll(true);
		view.setNode(root);
		root.add(new Html(null,null));
		FlexGrid form=new FlexGrid("form");
		root.add(form,"720");
		form.add("订单", 1, true);
		form.add(new Text("title","订单名称","").setNotnull(true),7);
		form.add("创建人", 1, false);
		form.add(new Html("[你]"), 3);
		form.add("详情", 1, false);
		GridLayout detail=new GridLayout("detail").setScroll(true);
		detail.setHeight("240").setCls("bd-mod").setHmin(2).setWmin(2).setScroll(true).setFace(GridLayout.FACE_LINE);
		form.add(detail, 11);
		fillDetail(detail);
		form.add("其他费", 1);
		form.add(new Spinner("orderPay", "其他费用",0.0 ,-999.00,999.00,1.00), 1);
		form.add("元",1);
		form.add("",1);
		form.add(new Html("除不尽的额外费用将随机分配给其中一些人"), 8);
		form.add("备注", 1);
		
		form.add(new Textarea("eventMessage", "备注", null),11);
		form.add("操作人", 1);
		form.add(new Html("[你]"), 5);
		form.add("操作时间", 1);
		form.add(new Html("[现在]"), 5);
		form.add(new Html(""), 5);
		form.add(new Button("提交").setCls("btn").setOn(Button.EVENT_CLICK,"VM(this).cmd('save')"), 5);

		root.add(new Html(null,null));
		view.addCommand("addRow", new AjaxCommand("gridShow/addRow?i=$0"));
		view.addCommand("save", new SubmitCommand("gridShow/save"));
		return view;
	}
	
	private void fillDetail(GridLayout detail) {
		//详情的构建
		detail.addColumn(GridColumn.text("U", "120"));
		detail.addColumn(GridColumn.text("FOOD", "*"));
		detail.addColumn(GridColumn.text("CNT", "105"));
		detail.addColumn(GridColumn.text("PR", "105"));
		detail.addColumn(GridColumn.text("OP", "60").setAlign(GridColumn.VALIGN_MIDDLE)
				.setFormat("<i class='x-grid-del' title='删除' onclick=\"" +
						"var vm=VM(this);" +
						"$.confirm('你确定要删除该条信息吗？'," +
						"function(){vm.find('tr$OP').remove()}"+
						");\"></i>"));

		List<String[]>  userOptions=getUserOption();
		Tr tr0=new Tr();
		detail.getThead().add(tr0);

		tr0.setData("U", "账号");
		tr0.setData("FOOD", "菜单");
		tr0.setData("CNT", "数量");
		tr0.setData("PR", "价格");
		tr0.setData("OP", "操作");
	
		

		List<Object[]> orderList=getOrderList(); 
		int i=0;
			for(Object[] order:orderList){
				i++;
				Tr tr=new Tr().setId("tr"+i);
				detail.add(tr);
				tr.setData("U", new XBox("personId"+i, "账号", order[0], userOptions));	
				tr.setData("FOOD", new Text("foodName"+i, "菜单", (String)order[1]));
				tr.setData("CNT", new Spinner("foodCount"+i, "数量", (Number)order[2],1,999,1));
				tr.setData("PR", new Spinner("foodPay"+i, "价格", (Number)order[3] ,0.0,999.0,1.0));
				tr.setData("OP",i);
			}
		detail.addHidden("index", String.valueOf(i));
		Tr btnRow=new Tr().setId("newLine");
		detail.add(btnRow);

		btnRow.setData("U", new Td().setColspan(5).setNode(new Html("<a href='#' onclick=\"VM(this).cmd('addRow',VM(this).fv('index'))\"><i class='x-grid-adduser'></i>&nbsp;新增一行</a>")));
		
	}

	private List<Object[]> getOrderList() {
		return Arrays.asList(new Object[][]{
				{"001","宫保鸡丁(套餐)",1,18.4},
				{"003","青菜素面",1,12.0},
				{"004","皇家套餐",1,99.9},
		});
	}

	private List<String[]> getUserOption() {
		return Arrays.asList(new String[][]{
				{"001","乔峰"},{"002","段誉"},{"003","虚竹"},{"004","慕容复"},{"005","王语嫣"},
		});
	}

	@RequestMapping("/addRow")
	@ResponseBody
	public Object addRow(HttpServletRequest request) throws Exception {
		String iStr=request.getParameter("i");
		int i=0;
		try{
			i=Integer.parseInt(iStr);
		}catch(Exception ex){}
		CommandGroup cg=new CommandGroup();
		List<String[]>  userOptions=getUserOption();

		i++;
		Tr tr=new Tr().setId("tr"+i);
		tr.setData("U", new XBox("personId"+i, "账号", null, userOptions));	
		tr.setData("FOOD", new Text("foodName"+i, "菜单", null));
		tr.setData("CNT", new Spinner("foodCount"+i, "数量", 1,1,999,1));
		tr.setData("PR", new Spinner("foodPay"+i, "价格", null ,0.0,999.0,1.0));
		tr.setData("OP",i);
		BeforeCommand before=new BeforeCommand();
		before.setTarget("newLine");
		before.add(tr);
		cg.add(before);
		
		cg.add(new JSCommand("VM(this).fv('index','"+i+"')"));
		
		return cg;
	}
	@RequestMapping("/save")
	@ResponseBody
	public Object save(HttpServletRequest request) throws Exception {
		String html=showRequestInfoAsHtml(request);
		DialogCommand dc=new DialogCommand();
		dc.setTemplate("std");
		dc.setTitle("提交的内容");
		dc.setWidth(DialogCommand.WIDTH_MEDIUM);
		dc.setHeight(DialogCommand.HEIGHT_LARGE);
		View view=PubView.buildDialogView();
		Html content=new Html(PubView.DIALOG_MAIN,html).setScroll(true);
		view.replaceNodeById(content);
		dc.setNode(view);
		return dc;
	}

	private String showRequestInfoAsHtml(HttpServletRequest request) {
		// TODO Auto-generated method stub
		StringBuilder sb=new StringBuilder();
		sb.append("<table class='request_info_table'>");
		Map<String,String[]>paramMap=request.getParameterMap();
		Map<String,String[]>headerMap=buildHeaderMap(request);
		buildTable("REQUEST",paramMap,sb);
		buildTable("HEADER",headerMap,sb);
		sb.append("</table>");
		return sb.toString();
	}

	private void buildTable(String title, Map<String, String[]> paramMap,StringBuilder sb) {
		sb.append("<tr><td colspan='2' class='subtitle'>");
		sb.append(title);
		sb.append("</td></tr>");
		for(Map.Entry<String, String[]> entry:paramMap.entrySet()){
			if(entry.getValue()==null||entry.getValue().length==0){
				continue;
			}else{
				sb.append("<tr><td class='t");
				if(entry.getValue().length>1){
					sb.append("' rowspan='")
						.append(entry.getValue().length);
				}
				sb.append("'>");
				sb.append(entry.getKey());
				sb.append("</td><td>");
				sb.append(Utils.escapeXMLword(entry.getValue()[0]));
				sb.append("</td></tr>");
				for(int i=1;i<entry.getValue().length;i++){
					sb.append("<tr><td>");
					sb.append(Utils.escapeXMLword(entry.getValue()[i]));
					sb.append("</td></tr>");
				}
			}
		}
	}

	private Map<String, String[]> buildHeaderMap(HttpServletRequest request) {
		TreeMap<String,String[]> map=new TreeMap<String,String[]>();
		Enumeration<String> headNames=request.getHeaderNames();
		while(headNames.hasMoreElements()){
			String hn=headNames.nextElement();
			List<String> values=new ArrayList<String>();
			Enumeration<String> headers=request.getHeaders(hn);
			while(headers.hasMoreElements()){
				String h=headers.nextElement();
				values.add(h);
			}
			map.put(hn, values.toArray(new String[values.size()]));
		}
		return map;
	}
}
